package com.example.ethereum.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.utils.Numeric;

@Slf4j
@Configuration
@ConfigurationProperties(prefix = "ethereum")
@Data
public class Web3jConfig {

    private String rpcUrl;
    private String privateKey;
    private Long chainId;
    private Long gasPrice;
    private Long gasLimit;

    @Bean
    public Web3j web3j() {
        return Web3j.build(new HttpService(rpcUrl));
    }

    @Bean
    public Credentials credentials() {
        if (privateKey == null || privateKey.isEmpty() || privateKey.equals("your-private-key-here")) {
            // 生成新的密钥对用于测试（仅用于开发环境）
            try {
                ECKeyPair keyPair = Keys.createEcKeyPair();
                privateKey = Numeric.toHexStringNoPrefix(keyPair.getPrivateKey());
                log.warn("Generated new private key for testing: {}", privateKey);
                log.warn("Please update application.properties with this private key for production use");
            } catch (Exception e) {
                throw new RuntimeException("Failed to generate credentials. Please provide a private key in application.properties", e);
            }
        }
        return Credentials.create(privateKey);
    }

    @Bean
    public DefaultGasProvider gasProvider() {
        return new DefaultGasProvider() {
            @Override
            public java.math.BigInteger getGasPrice() {
                return java.math.BigInteger.valueOf(gasPrice);
            }

            @Override
            public java.math.BigInteger getGasLimit() {
                return java.math.BigInteger.valueOf(gasLimit);
            }
        };
    }
}

